#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>

using namespace std;

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
    ui->setupUi(this);
    capThread = new CaptureThread(this);
    playThread = new PlayThread(this);
    connect(ui->actionAbrir_Video, SIGNAL(triggered()), this, SLOT(prepare_connection()));
    connect(ui->actionDisconnect_Camera, SIGNAL(triggered()), this, SLOT(disconnect_camera()));
    connect(this,SIGNAL(startThread()),this,SLOT(call_startThread()));
    connect(ui->pushButton,SIGNAL(clicked()),capThread,SLOT(save_vector()));
    connect(capThread,SIGNAL(update_status(QString)),this,SLOT(change_statusApp(QString)));
    connect(playThread,SIGNAL(show_now()),this,SLOT(showNextFrame()));
    change_statusApp("Ready to work...");
    camDialog = NULL;
}

MainWindow::~MainWindow() {
    delete ui;
}

void MainWindow::prepare_connection() {

    if(camDialog==NULL) {
        camDialog = new CameraDialog(camParams, this);
        connect(camDialog,SIGNAL(data_ready()), this, SLOT(ready_camera()));
    }
    camDialog->show();
}

void MainWindow::change_statusApp(QString texto) {
    ui->status_box->setText(texto);
}

void MainWindow::print_frame(Mat &frame)
{
    int w,h,bpl,step,ch;
    uchar *pix_in, *pix;

    w    = frame.cols;
    h    = frame.rows;
    step = frame.step;
    ch   = frame.channels();

    pix_in = frame.data;

    QImage imagen(w,h,QImage::Format_RGB32);

    pix = imagen.bits();
    bpl = imagen.bytesPerLine();

    for(int j=0; j<h; j++)
        for(int i=0; i<w; i++) {
            pix[j*bpl+i*4+0] = pix_in[j*step+i*ch+0];
            pix[j*bpl+i*4+1] = pix_in[j*step+i*ch+1];
            pix[j*bpl+i*4+2] = pix_in[j*step+i*ch+2];
            //pix[j*bpl+i*4+3] = 255;
        }


    ui->label->setPixmap(QPixmap::fromImage(imagen));

}

void MainWindow::disconnect_camera() {
    capThread->stop();
}

void MainWindow::ready_camera() {

    if(camParams.option==OPTION_LOCAL_CAMERA){
        QString path = camParams.deviceId;
        int devId=0;
        path.remove("/dev/video");
        devId = path.toInt();
        /// Se tiene el indice de la camara a conectar
        if(capThread->connect_localcamera(devId)){
            change_statusApp("Connection succeded to "+camParams.deviceId);
            emit startThread();
        }
        else
            change_statusApp("Impossible connecting to: "+camParams.deviceId);

    } else if(camParams.option==OPTION_IP_CAMERA) {
        /// Se tiene la informacion para conectar con la camara ip
        QString path("rtsp://"+camParams.ipUser+":"+camParams.ipPass+"@"+camParams.ipUrl+":"+camParams.ipPort+"/mpeg4/media.amp");
        QString showable("rtsp://"+camParams.ipUser+":"+"*****"+"@"+camParams.ipUrl+":"+camParams.ipPort+"/mpeg4/media.amp");
        if(capThread->connect_ipcamera(path, showable)){
            change_statusApp("Connection succeded to: "+showable);
            emit startThread();
        }
        else
            change_statusApp("Impossible connecting to: "+showable);
    } else {
        change_statusApp("There was an error loading the information from the dialog");
    }
}

void MainWindow::call_startThread() {
    capThread->start(QThread::InheritPriority);
}

void MainWindow::on_pushButton_2_clicked()
{
    int total = capThread->getNoFrames();
    vector<int> tiempos(total,0);

    for(int i=0; i<total; i++)
        tiempos[i] = capThread->getFrameAt(i).dtime;

    playThread->setDtime(tiempos);
    playThread->start(QThread::InheritPriority);
}

void MainWindow::showNextFrame() {
    static int actual=0;
    Frame frame;

    if(!capThread->frameExists(actual)) {
        change_statusApp("No more frames. Stopped at frame #"+QString::number(actual));
        playThread->stop();
        return;
    }

    frame.dtime = capThread->getFrameAt(actual).dtime;
    capThread->getFrameAt(actual).image.copyTo(frame.image);

    change_statusApp("dtime de imagen #"+QString::number(actual)+": "+QString::number(frame.dtime));
    actual++;
    print_frame(frame.image);
}
